package com.gaohe.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gaohe.common.BaseContext;
import com.gaohe.common.R;
import com.gaohe.common.S;
import com.gaohe.common.SMSSendCode;
import com.gaohe.pojo.*;
import com.gaohe.service.*;
import com.gaohe.utils.CodeUtils;
import com.gaohe.utils.RegexUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private CardService cardService;
    @Autowired
    private ClassesService classesService;
    @Autowired
    private UserCardService userCardService;
    @Autowired
    private RedisTemplate redisTemplate;

    private static final String teacher = "老师";
    private static final String vip = "会员";


    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R page(@RequestParam("page") Integer page,
                  @RequestParam("pageSize") Integer pageSize,
                  @RequestParam(value = "name", required = false) String name,
                  @RequestParam("type") String type) {
        log.info("用户分页查询");
        Page<User> userPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(!ObjectUtils.isEmpty(name), User::getName, name);
        queryWrapper.eq(User::getType, type);
        queryWrapper.orderByDesc(User::getUpdateTime);
        queryWrapper.orderByAsc(User::getName);
        userService.page(userPage, queryWrapper);
        //log.info("用户信息：{}",userPage.getRecords());
        return R.success(userPage);
    }

    /**
     * 查看老师
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/teacher/page")
    public R findTeacher(Integer page, Integer pageSize) {
        Page<User> userPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
        qw.eq(User::getType, teacher);
        userService.page(userPage, qw);
        return R.success(userPage);
    }


    /**
     * 新增老师
     *
     * @param user
     * @return
     */
    @PostMapping("/teacher")
    public R addTeacher(@RequestBody User user) {
        log.info("新增信息:{}", user);
        user.setUpdateTime(LocalDateTime.now());
        user.setType(teacher);
        boolean save = userService.save(user);
        return save ? R.success("新增成功") : R.error("新增失败");
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    @GetMapping("/teacher/{id}")
    public R findById(@PathVariable("id") Long id) {
        User user = userService.getById(id);
        return R.success(user);
    }

    /**
     * 更新
     *
     * @param user
     * @return
     */
    @PutMapping("/teacher")
    public R update(@RequestBody User user) {
        user.setUpdateTime(LocalDateTime.now());
        boolean update = userService.updateById(user);
        return update ? R.success("修改成功") : R.error("修改失败");
    }

    /**
     * 禁用启用
     *
     * @param user
     * @return
     */
    @PutMapping("/status")
    public R status(@RequestBody User user) {
        user.setUpdateTime(LocalDateTime.now());
        userService.updateById(user);
        return R.success(user.getStatus() == 1 ? S.ENABLE_SUCCESS : S.DISABLE_SUCCESS);
    }

    /**
     * 课程查询老师姓名
     *
     * @return
     */
    @GetMapping("/teacher")
    public R getTeacher() {
        LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
        qw.eq(User::getType, teacher);
        List<User> teacherList = userService.list(qw);
        return R.success(teacherList);
    }

    /**
     * 新增会员
     *
     * @param user
     * @return
     */
    @PostMapping("/user")
    public R insertUser(@RequestBody User user) {
        user.setType(vip);
        user.setUpdateTime(LocalDateTime.now());
        boolean save = userService.save(user);
        return save ? R.success(S.INSERT_SUCCESS) : R.error(S.INSERT_ERROR);
    }

    /**
     * 查看会员
     *
     * @param id
     * @return
     */
    @GetMapping("/user/{id}")
    public R getByID(@PathVariable Long id) {
        User user = userService.getById(id);
        return R.success(user);
    }

    /**
     * 会员修改
     *
     * @param user
     * @return
     */
    @PutMapping("/user")
    public R updateUser(@RequestBody User user) {
        user.setUpdateTime(LocalDateTime.now());
        boolean b = userService.updateById(user);
        return b ? R.success(S.UPDATE_SUCCESS) : R.error(S.UPDATE_ERROR);
    }

    /**
     * 根据会员 id 查询会员卡
     *
     * @param id
     * @return
     */
    @GetMapping("/userCards/{id}")
    public R getCardsByUserId(@PathVariable("id") Long id) {
        LambdaQueryWrapper<UserCard> qw = new LambdaQueryWrapper<>();
        qw.eq(UserCard::getUserId, id);
        List<UserCard> userCards = userCardService.list(qw);
        return R.success(userCards);
    }

    /**
     * 选卡
     *
     * @param cardId
     * @param paramUser
     * @return
     */
    @PostMapping("/user/saveByCardId/{id}")
    public R saveCardById(@PathVariable("id") Long cardId,
                          @RequestBody User paramUser) {
        /**
         * 1.卡的状态是否起售
         * 2.用户是否禁用
         * 3.赋值
         * 4.新增
         */
        Card card = cardService.getById(cardId);
        User user = userService.getById(paramUser.getId());
        if (card.getStatus() != S.STATUS_OPEN) {
            return R.error("会员卡已经停售，不可选");
        }
        if (user.getStatus() != S.STATUS_OPEN) {
            return R.error("会员被禁用，无法选卡");
        }
        //根据 userid 查卡
        LambdaQueryWrapper<UserCard> qw = new LambdaQueryWrapper<>();
        qw.eq(UserCard::getUserId, paramUser.getId());
        List<UserCard> userCardList = userCardService.list(qw);
        for (UserCard userCard : userCardList) {
            //判断用户是否有 要选择的卡
            if (userCard.getCardId().equals(cardId)) {
                // 次卡  isdeleted  直接选  有  不可重复选
                if (userCard.getType().equals("次卡") && userCard.getIsDeleted() != 1) {
                    return R.error("会员已有此卡，不可新增");
                }
                //期限卡  有 isdeleted ==0  更新
                if (userCard.getType().equals("期限卡") && userCard.getIsDeleted() != 1) {
                    userCard.setEndDate(userCard.getStartDate().plusDays(card.getDay()));
                    boolean b = userCardService.updateById(userCard);
                    return b ? R.success("选卡成功") : R.error("选卡失败");
                }
            }
        }
        //赋值
        UserCard userCard = new UserCard();
        BeanUtils.copyProperties(card, userCard, "id");
        userCard.setCardId(cardId);
        userCard.setCardName(card.getName());
        userCard.setUserId(paramUser.getId());
        userCard.setStartDate(LocalDate.now());
        userCard.setEndDate(LocalDate.now().plusDays(card.getDay()));
        boolean save = userCardService.save(userCard);
        return save ? R.success(S.INSERT_SUCCESS) : R.error(S.INSERT_ERROR);
    }

    /**
     * 根据会员 id 查询 课程
     *
     * @param userId
     * @return
     */
    @GetMapping("/userClasses/{id}")
    public R getClassesByUserId(@PathVariable("id") Long userId) {
        List<Classes> classesList = classesService.getByUserId(userId);
        return R.success(classesList);
    }

    /**
     * 根据老师 id 查询 课程
     *
     * @param tid
     * @return
     */
    @GetMapping("/teacher/classes/{id}")
    public R getClassesByTeacherId(@PathVariable("id") Long tid) {
        LambdaQueryWrapper<Classes> qw = new LambdaQueryWrapper<>();
        qw.eq(Classes::getTeacherId, tid);
        List<Classes> classesList = classesService.list(qw);
        return R.success(classesList);
    }

    /*-------------------小程序端处理----------------*/

    /**
     * 获取验证码
     *
     * @param map
     * @return
     */
    @PostMapping("sendMsg")
    public R sendMsg(@RequestBody Map<String, String> map) {
        //1.验证手机号格式是否正确   -- 正则表达式
        String phone = map.get("phone");
        if (!RegexUtils.isPhoneNumber(phone)) {
            return R.error("手机号格式错误");
        }
        //2.发送验证码
        Integer code = CodeUtils.generateValidateCode(4);
      /*  try {
            SMSSendCode.sendCode(phone,String.valueOf(code));
        } catch (Exception e) {
            e.printStackTrace();
        }*/
        //验证码存redis
        redisTemplate.opsForValue().set(
                "code" + phone,
                String.valueOf(code),
                5,
                TimeUnit.MINUTES);
        log.info("code:{}", code);
        //响应结果
        return R.success("发送成功");
    }

    /**
     * 小程序登录
     *
     * @param map
     * @return
     */
    @PostMapping("/login")
    public R login(@RequestBody Map<String, String> map) {
        //获取 手机号 -- 验证格式
        String phone = map.get("phone");
        if (!RegexUtils.isPhoneNumber(phone)){
            return R.error("手机号输入有误");
        }
        //获取验证码  判断验证码
        String code = map.get("code");
        if (ObjectUtils.isEmpty(code)){
            return R.error("验证码不能为空");
        }
        Object o = redisTemplate.opsForValue().get("code" + phone);
        if (ObjectUtils.isEmpty(o)){
            return R.error("验证码过期");
        }
        String rCode = (String) o;
        if (!rCode.equals(code)){
            return R.error("验证码输入错误");
        }
        //type  -- 必须选  判空
        String type = map.get("type");
        if (ObjectUtils.isEmpty(type)){
            return R.error("请选择身份信息");
        }
        // 根据手机号查询  有  
        LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
        qw.eq(User::getPhone,phone);
        User user = userService.getOne(qw);
        // 账号是否被  禁用  0
        if (ObjectUtils.isNotEmpty(user) && user.getStatus()  == 0){
            return R.error("账号被禁用");
        }
        //判断身份选择是否则正确
        if (ObjectUtils.isNotEmpty(user) && (!user.getType().equals(type))){
            return R.error("请正确选择身份");
        }
        // 会员 -- 注册 
        // 老师 -- 管理员  
        if (ObjectUtils.isEmpty(user)){
            if (type.equals("会员")){
                // 注册
                User newUser = new User();
                newUser.setName("vip"+phone);
                newUser.setPhone(phone);
                newUser.setBirthday(LocalDate.now());
                newUser.setImage("7d62feeb-9b88-49f3-87c5-e4b5f189e948.jpg");
                newUser.setStatus(1);
                newUser.setType(type);
                newUser.setIsDeleted(0);
                newUser.setCreateTime(LocalDateTime.now());
                newUser.setUpdateTime(LocalDateTime.now());
                newUser.setCreateUser(123L);
                newUser.setUpdateUser(123L);
                boolean save = userService.save(newUser);
                redisTemplate.opsForValue().set(
                        "auth"+newUser.getId(),
                        newUser.getId(),
                        30,TimeUnit.MINUTES);
                return save?R.success(newUser):R.error("登录失败");
            }
            if(type.equals("老师")){
                return R.error("请联系管理员申请账号");
            }
        }
        //返回登录成功的结果
       // User user = userService.getById(1001);
        //User user = userService.getById(1002);
        redisTemplate.opsForValue().set(
                "auth"+user.getId(),
                user.getId(),
                30,TimeUnit.MINUTES);
        BaseContext.setCurrentId(user.getId());
        return R.success(user);
    }

    /**
     * 根据用户id和会员卡id判断此卡是否已持有 用户端
     * @param userId
     * @param cardId
     * @return
     */
    @GetMapping("/getSelectedCard")
    public R getSelectedCard(@RequestParam Long userId, @RequestParam Long cardId) {
        UserCard userCard = userCardService.getByUserIdAndCardId(userId, cardId);
        return ObjectUtils.isEmpty(userCard) ? R.success("可以购买") : R.error("已有此卡");
    }

}
